//
//  SubTableView.m
//  SubTableExample
//
//  Created by Alex Koshy on 7/16/14.
//  Copyright (c) 2014 ajkoshy7. All rights reserved.
//

#import "SubTableView.h"
//#import "SubTableViewCell.h"


@implementation SubTableView

@synthesize insideTableView;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
        [[self contentView] setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
//        NSString *str1=[NSString stringWithFormat:@"%d",TARGET_VERSION];
//        if ([str1 isEqualToString:@"4"]||[str1 isEqualToString:@"14"]||[str1 isEqualToString:@"6"]||[str1 isEqualToString:@"16"]) {//
//            NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"P006Home" ofType:@"plist"];
//            NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
//            parentArray= [[dictionary objectForKey:@"HomeSlider"] objectForKey:@"ParentTextArray"];
//            subArray=[[dictionary objectForKey:@"HomeSlider"] objectForKey:@"SubTextArray"];
//            //        fgColor = [UIColor colorWithRed:150/255 green:150/255 blue:150/255 alpha:1.0];
//            //        bgColor = [UIColor clearColor];
//            font = [UIFont systemFontOfSize:14.0];
//            [self configureInsideTableView];
//
//            
//        }else{
//            
//            NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"P009Home" ofType:@"plist"];
//            NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
//            parentArray= [[dictionary objectForKey:@"HomeSlider"] objectForKey:@"ParentTextArray"];
//            subArray=[[dictionary objectForKey:@"HomeSlider"] objectForKey:@"SubTextArray"];
//            //        fgColor = [UIColor colorWithRed:150/255 green:150/255 blue:150/255 alpha:1.0];
//            //        bgColor = [UIColor clearColor];
//            font = [UIFont systemFontOfSize:14.0];
//            [self configureInsideTableView];
//
//            
//        }
        font = [UIFont systemFontOfSize:14.0];
        [self configureInsideTableView];

          }
    return self;
}



#pragma mark - Configuration

- (void)configureInsideTableView {
    
    self.insideTableView = [[UITableView alloc] init];
    insideTableView.frame = CGRectMake(0, 0, self.contentView.frame.size.width, self.contentView.frame.size.height);
    
    insideTableView.dataSource = self;
    insideTableView.delegate = self;
    
    [self.insideTableView setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
    insideTableView.scrollEnabled = NO;
    
    insideTableView.backgroundColor = [UIColor clearColor];
    insideTableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    //insideTableView.separatorColor = [UIColor colorWithWhite:( 70/255.0) alpha:1.0];
    [insideTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.contentView addSubview:self.insideTableView];
}



#pragma mark - Getters/Setters

/***
 * Delegate
 */
- (id)getDelegate {
    return delegate;
}
// TODO combine set delegate and parentIndex into one method for better safety
- (void)setDelegate:(id<SubTableViewCellDelegate>)deleg {
    
    delegate = deleg;
    NSInteger numberOfChild = [delegate numberOfChildrenUnderParentIndex:self.parentIndex];

    NSInteger rowHeight = [delegate heightForChildRows];
    insideTableView.frame = CGRectMake(0, 0, self.contentView.frame.size.width, rowHeight * numberOfChild);
    
//    NSString * parentIndexStr=[NSString stringWithFormat:@"%ld",(long)self.parentIndex];
    parentIndexKeyStr=[NSString stringWithFormat:@"parent%ld",(long)self.parentIndex];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
   
    if ([userDefaults objectForKey:parentIndexKeyStr]) {
//        addOrSubTractDict=[NSMutableDictionary  dictionaryWithDictionary:[userDefaults dictionaryForKey:parentIndexKeyStr]];
//        NSMutableArray *saveArray=[NSMutableArray arrayWithArray:[addOrSubTractDict objectForKey:@"addOrSubtractARRAY"]];
//        NSMutableArray *subTextUnderParentIndexArray=[subArray objectAtIndex:self.parentIndex];
//         NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
//         NSMutableArray *arr=[NSMutableArray array];
////         NSLog(@"V###====%@",subTextUnderParentIndexArray);
//        
//        for (int i=0; i<subTextUnderParentIndexArray.count; i++) {
//            if (saveArray.count-1>=i) {
//                
//                [arr addObject: saveArray[i]];
////                 NSLog(@"arr###====%@",arr);
//            }
//            else
//            {
//                [arr addObject:@"N"];
////                 NSLog(@"arr###0====%@",arr);
//            }
//        }
//        [dict setValue:arr forKey:@"addOrSubtractARRAY"];
//        [userDefaults setObject:dict forKey:parentIndexKeyStr];
//        
//        [[NSUserDefaults standardUserDefaults] synchronize];
        
        addOrSubTractDict=[NSMutableDictionary  dictionaryWithDictionary:[userDefaults dictionaryForKey:parentIndexKeyStr]];
        addOrSubtractArray=[NSMutableArray arrayWithArray:[addOrSubTractDict objectForKey:@"addOrSubtractARRAY"]];

    }
    else
    {
        
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSMutableArray* itemsArray = [user objectForKey:@"itemsArray"];

        
        for (int j=0; j<itemsArray.count; j++) {
         NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
         NSMutableArray *arr=[NSMutableArray array];
         NSString *parentKeyStr=[NSString stringWithFormat:@"parent%ld",(long)j];
         NSInteger childCount = [delegate numberOfChildrenUnderParentIndex:j];

        for (int i=0; i<childCount; i++) {
           if (j==0&&(i==0||i==1)) {
                [arr addObject:@"Y"];
            }
            else if (j==1&&(i==0||i==1||i==2)) {
                [arr addObject:@"Y"];
            }
            else if (j==2&&(i==0||i==1||i==2)) {
                [arr addObject:@"Y"];
            }
            else
            {
                 [arr addObject:@"N"];
            }
           
        }
            [dict setValue:arr forKey:@"addOrSubtractARRAY"];
            [userDefaults setObject:dict forKey:parentKeyStr];
            
            [[NSUserDefaults standardUserDefaults] synchronize];
    }
       
        addOrSubTractDict=[NSMutableDictionary  dictionaryWithDictionary:[userDefaults dictionaryForKey:parentIndexKeyStr]];
        addOrSubtractArray=[NSMutableArray arrayWithArray:[addOrSubTractDict objectForKey:@"addOrSubtractARRAY"]];

       
    }
    


}
- (void)resetDefaults {
    NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
    NSDictionary * dict = [defs dictionaryRepresentation];
    for (id key in dict) {
        for ( int i=0; i<parentArray.count; i++) {
            NSString *parentKeyStr= [NSString stringWithFormat:@"parent%ld",(long)i];
        if ([key isEqualToString:parentKeyStr]) {
            [defs removeObjectForKey:key];
        }
        }
        
    }
    [defs synchronize];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}
- (void)reload {
    [self.insideTableView reloadData];
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   
    NSInteger count= [self.delegate numberOfChildrenUnderParentIndex:self.parentIndex];
    if (count > 0)
        return count;
    else
        return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //static NSString *CELL_IDENTIFIER = @"SubTableViewCell_Reuse_Id";
    
    static NSString * const SecondLevelTableViewCellIdentifier = @"subNewTableViewCell";
    subNewTableViewCell *cell=(subNewTableViewCell *)[tableView dequeueReusableCellWithIdentifier:SecondLevelTableViewCellIdentifier];
    if (cell==nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"subNewTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
    }
    cell.delegate=self;
        
    NSInteger row = [indexPath row];
    cell.titleLable.text = [self.delegate titleLabelForChildIndex:row underParentIndex:self.parentIndex];
    [cell.iconImageView setImage:[self.delegate iconForCellAtChildIndex:row underParentIndex:self.parentIndex]];
    cell.addOrSubtractBtn.tag=indexPath.row;
    if ([[addOrSubtractArray objectAtIndex:indexPath.row] isEqualToString:@"N"]) {
        [cell.addOrSubtractBtn setImage:[UIImage imageNamed:@"tianjia_new"] forState:UIControlStateNormal];
    }
    else
    {
        [cell.addOrSubtractBtn setImage:[UIImage imageNamed:@"yitianjia_new"] forState:UIControlStateNormal];
        
        
    }
    return cell;
}

-(void)subAddOrSubtractBtnClick:(NSUInteger)tag
{
    int num=0;
     NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    for ( int i=0; i<parentArray.count; i++) {
    NSString *parentKeyStr= [NSString stringWithFormat:@"parent%ld",(long)i];
        NSMutableDictionary *dict=[NSMutableDictionary  dictionaryWithDictionary:[userDefaults dictionaryForKey:parentKeyStr]];
        
         NSMutableArray *array=[NSMutableArray arrayWithArray:[dict objectForKey:@"addOrSubtractARRAY"]];
        for (int j=0; j<array.count; j++) {
            if ([[array objectAtIndex:j]isEqualToString:@"Y"]) {
                num++;
                
            }
        }
    }
     NSString *str=[addOrSubtractArray objectAtIndex:tag];
    NSIndexPath *indexPath1= [NSIndexPath indexPathForRow:tag inSection:0];
    UITableViewCell *cell = [insideTableView cellForRowAtIndexPath:indexPath1];
    subNewTableViewCell *subCell=( subNewTableViewCell *)cell;
    if ([str isEqualToString:@"N"] ) {
        
  //  if (num<8) {
  //  NSString *str=[addOrSubtractArray objectAtIndex:tag];
   // if ([str isEqualToString:@"N"]) {
        str=@"Y";
        num++;
       [subCell.addOrSubtractBtn setImage:[UIImage imageNamed:@"yitianjia_new"] forState:UIControlStateNormal];
   // }
      
    
        [addOrSubtractArray replaceObjectAtIndex:tag withObject:str];
        [addOrSubTractDict setValue:addOrSubtractArray forKey:@"addOrSubtractARRAY"];
        [userDefaults setObject:addOrSubTractDict forKey:parentIndexKeyStr];
        
        [[NSUserDefaults standardUserDefaults] synchronize];
//    }
//    else
//    {
//        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"最多加入8个" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [alert show];
//    }


    }
    else if ([str isEqualToString:@"Y"] )
    {
        str=@"N";
         num--;
        [subCell.addOrSubtractBtn setImage:[UIImage imageNamed:@"tianjia_new"] forState:UIControlStateNormal];
        
  
        [addOrSubtractArray replaceObjectAtIndex:tag withObject:str];
        [addOrSubTractDict setValue:addOrSubtractArray forKey:@"addOrSubtractARRAY"];
        [userDefaults setObject:addOrSubTractDict forKey:parentIndexKeyStr];
        
        [[NSUserDefaults standardUserDefaults] synchronize];
   
}
[self.delegate subTableviewCellSubtractOrAdd];
   // NSLog(@"addOrSubTractDict===%@",addOrSubTractDict);
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    return [delegate heightForChildRows];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // must be implemented by concrete subclasses
    
   
}

@end
